import { createStore } from 'vuex';
import { req_login, req_logout, req_userGet } from '/src/api';
import { response2ElMessage } from '/src/utils/response-utils';

const notLoggedInUser = {
  user_id: -1,
  scholar_id: "",
  user_name: "",
  email: "",
  introduction: "",
  user_type: "",
  scholar_name:""
};

const store = createStore({
  state: {
    /** 登录状态 */
    hasLogin: false,

    /** 登录用户 */
    user: notLoggedInUser,
  },
  mutations: {
    clearUser(state) {
      state.hasLogin = false;
      state.user = notLoggedInUser;
    },
    setUser(state, user) {
      state.hasLogin = true;
      state.user = user;
    },
  },
  actions: {
    async userGet({ commit }) {
      try {
        let response = await req_userGet();
        let data = response.data;
        let user = data['user'];

        switch (data['errno']) {
          case 1:
            commit('setUser', {
              user_name: user['user_name'],
              email: user['email'],
              introduction: user['introduction'],
              scholar_id: user['scholar_id'],
              user_type: user['user_type'],
              user_id: user['user_id'],
              scholar_name: user['scholar_name'],
            });
            break;
          case -3:
            commit('clearUser');
            break;
        }
      } catch (error) {
        console.error('userGet action failed:', error);
        // 处理异常，例如显示错误消息
      }
    },
  },
  modules: {},
});
export default store;
